

using System;
using System.Data;
using System.IO;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Expressions;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Abp.Linq;
using Abp.Linq.Extensions;
using Abp.Extensions;
using Abp.UI;
using Abp.Domain.Repositories;
using Abp.Domain.Services;

using Yozeev;
using Yozeev.SystemConfig;
using Yozeev.UserManagerment.Users;
using Yozeev.SystemConfig.BasicConfig;

namespace Yozeev.SystemConfig.DomainService
{
    /// <summary>
    /// BranchUser领域层的业务管理
    ///</summary>
    public class BranchUserManager :YozeevDomainServiceBase, IBranchUserManager
    {
		
		private readonly IRepository<BranchUser,Guid> _repository;

		/// <summary>
		/// BranchUser的构造方法
		///</summary>
		public BranchUserManager(
			IRepository<BranchUser, Guid> repository
		)
		{
			_repository =  repository;
		}


		/// <summary>
		/// 初始化
		///</summary>
		public void InitBranchUser()
		{
			throw new NotImplementedException();
		}

		// TODO:编写领域业务代码
		/// <summary>
		/// 根据用户查询机构用户
		/// </summary>
		/// <param name="user"></param>
		/// <returns></returns>
		public async Task<BranchUser> GetBranchUser(User user)
		{
			return await _repository.FirstOrDefaultAsync(m => m.UserId == user.Id);
		}

		public async Task CreateBranchUser(long userId,Guid branchId )
		{
			await _repository.DeleteAsync(m => m.UserId == userId);
			var branchUser = new BranchUser()
			{
				UserId = userId,
				BranchId = branchId,
			};
			await _repository.InsertAndGetIdAsync(branchUser);
		}

		public async Task<Branch> GetBranchByUser(User user)
		{
			var list = _repository.GetAll().Where(m => m.UserId == user.Id).Select(m => m.Branch);
			return await list.FirstOrDefaultAsync();
		}

	}
}
